#include "error.h"
#include <ctime>
#include <cstdarg>
#include <cstdlib>

static void make_tstring(char* str,size_t sz){
    time_t timestamp;
    time(&timestamp);
    strftime( str, sz, "%a %b %d %Y %X", localtime( &timestamp ));
}

namespace error{

FILE* err_file;

    void setFile(const char* fname){
        err_file = fopen(fname,"w");
        char tbuf[255];
        make_tstring(tbuf,255);
        fprintf(err_file,"[%s]Starting logging\n",tbuf);
        printf("[%s]Starting logging\n",tbuf);
        fflush(err_file);
    }
    void end(){
        char tbuf[255];
        make_tstring(tbuf,255);
        fprintf(err_file,"[%s]Ending logging\n",tbuf);
        printf("[%s]Ending logging\n",tbuf);
        fflush(err_file);
        fclose(err_file);
    }
    void log(error::err_type type,const char* format,...){
        char tbuf[255];
        make_tstring(tbuf,255);
        char buffer[1024];
        va_list vargs;
        va_start(vargs,format);
        vsprintf(buffer,format,vargs);
        va_end(vargs);
        if( type == con_only ) printf("%s",buffer);
        else if( type == log_info ){
            printf("[%s]<Info>%s\n",tbuf,buffer);
            fprintf(err_file,"[%s]<Info>%s\n",tbuf,buffer);
        }
        else if( type == log_err ){
            printf("[%s]<Error>%s\n",tbuf,buffer);
            fprintf(err_file,"[%s]<Error>%s\n",tbuf,buffer);
        }
        else if( type == log_warn ){
            printf("[%s]<Warning>%s\n",tbuf,buffer);
            fprintf(err_file,"[%s]<Warning>%s\n",tbuf,buffer);
        }
        else if( type == log_ferr ){
            printf("[%s]<Fatal Error>%s\n",tbuf,buffer);
            fprintf(err_file,"[%s]<Fatal Error>%s\n",tbuf,buffer);
            end();
            exit(EXIT_FAILURE);
        }
    }

}
